package xq.gwt.ui.widgets.property;

import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import xq.gwt.mvc.model.PropertyModel;
import xq.gwt.ui.widgets.factory.FormItemPropertyPresenterFactory;

public class PropertyListPresenter {
	private DynamicForm form;	
	private FormItemPropertyPresenter[] propertyPresenters;
	
	public PropertyListPresenter(){
		form = new DynamicForm();
		init();
	}
	
	public PropertyListPresenter(DynamicForm form){
		this.form = form;
		init();
	}
	
	private void init() {
		form.addDrawHandler(new DrawHandler() {
			@Override
			public void onDraw(DrawEvent event) {
				if (propertyPresenters != null) {
					for (int i = 0; i < propertyPresenters.length; i++) {
						propertyPresenters[i].validate();
					}
				}
			}
		});
	}
	
	
	public void setProperties(PropertyModel[] props){
		if(props == null)
			return;		
		propertyPresenters = FormItemPropertyPresenterFactory.buildPresenters(props);		
		FormItem[] formItems = new FormItem[propertyPresenters.length];
		for (int i = 0; i < propertyPresenters.length; i++) {
			formItems[i] =propertyPresenters[i].getFormItem();
		}	
		
		form.setFields(formItems);		
	}
	
	public DynamicForm getForm() {
		return form;
	}

	public FormItemPropertyPresenter[] getPopertyPresenters(){
		return propertyPresenters;
	}
}
